<?php


namespace App\Services;

use Swoole\Http\Request;
use Swoole\WebSocket\Server;

class DialogueStateService
{
    /**
     * im 登录上线
     * @param Server $server
     * @param Request $request
     */
    public static function doLogin(Server $server, Request $request): void
    {
        $user = auth('api')->user();

        if (is_null($user)) {
            $server->push($request->fd, error('token check failed'));
            $server->close($request->fd);
        } else {
            self::checkOnline($server, $user->id);
            UserLineService::setOnline($user, $request->fd);
            $server->push($request->fd, success('login success'));
        }
    }

    /**
     * 单点登录
     *
     * @param \Swoole\WebSocket\Server $server
     * @param $userId
     */
    public static function checkOnline($server, $userId): void
    {
        $afterFd = (int)redis()->hGet('user_id_to_fd', (string)$userId);

        if (is_bool($afterFd)) {
            return;
        }

        if ($server->isEstablished($afterFd)) {
            $server->push($afterFd, error('you account login other location'));
            UserLineService::setOutline($server, $afterFd);
        }
    }
}